import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-09-28
 * Time: 13:33
 */
class Solution11 {
    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,-1,1};

    public int nearestExit(char[][] maze, int[] entrance) {
        int m = maze.length;
        int n = maze[0].length;
        boolean[][] visit = new boolean[m][n];

        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{entrance[0],entrance[1]});
        visit[entrance[0]][entrance[1]] = true;

        int step = 0;
        while(!q.isEmpty()) {
            step++;
            int size = q.size();
            for(int i = 0; i < size; i++) {
                int[] t = q.poll();
                int a = t[0],b = t[1];
                for(int j = 0; j < 4; j++) {
                    int x = a+dx[j],y = b+dy[j];
                    if(x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == '.' && !visit[x][y]) {
                        if(x == 0 || x == m-1 || y == 0 || y == n-1) {
                            return step;
                        }
                        q.add(new int[]{x,y});
                        visit[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
}